define(function(require,exports,module) {
    var myPub = require('./public');
    var adsModel = require('./adsModel');

    var oWindow = $(window);
    var oWrap = $('.js_wrap');                      // wrap 部分
    var oHeader = $('.js_headerBox');               // 头部
    var oFooter = $('.js_footer');                  // 底部
    var oContain = $('.js_contain');                // 页面内容区域
    var oSideBox = $('.js_sideBox');		        // 侧边按钮框

    var oShowSearchBox = $('.js_showSearchBox');       //搜索按钮
    var oClearSear = $('.js_clearSearchAndCover');     //搜索层的返回键
    var oGoods_showTwo = $('.js_goods_showTwo');        // 并排产品容器

    var oSlidePageScroll = $('.js_slidePageScroll');
    var lazLoading = new myPub.lazLoadingImg();

    var perLimit = 20;
    var resizeTimer = null;

    $('.guideShow').on("touchmove",function(e) {e.preventDefault()});
    oHeader.on("touchmove",function(e) {e.preventDefault()});
    oFooter.on("touchmove",function(e) {e.preventDefault()});


    //<!-- 广告弹框 -->
    $('.layer_AdsCloseBtn').hammer().on('click', function (e) {
        $('.layer_Ads_index').hide();
        myPub.HamstopPropaga();
        e.preventDefault()
    });
    module.exports = {
        init: function(data,names) {
            sfddjIndex.sfddjInit(true);
            sfddjIndex.ScrollPage();

            // 历史数据初始化
            ajaxData.HistoryInit();

            // 请求加载广告模块
            adsModel.adsAjax.AdsAjaxData(0, names);

            adsModel.adsInit.CutDataTime();

            lazLoading.AddLazLoadingImg(oWrap[0]);

            //点击搜索按钮弹出搜索层
            sfddjIndex.showSearchBox();

            // 获取弹窗
            adsModel.adsAjax.getPop();

            // 页面尺寸修改
            oWindow.on('resize',function() {
                if (resizeTimer) {
                    clearTimeout(resizeTimer)
                }
                resizeTimer = setTimeout(function(){
                    sfddjIndex.sfddjInit(true);
                }, 400);

            });

            // 页面跳转记录数据
            oWindow.unload(function(){
               ajaxData.SetSession();
            });
        }
    };



    var ajaxData = {
        limit: 4,                           // 每次加载多少数据
        tabLoadOff: [false],                // 左右滑动加载开关
        pagearr: 1,                         // 每个分页的翻页数
        pageScroll: 0,                      // 每个分页滚动高度
        loadFinish: false,                  // 加载完成

        // 设置商品数据
        GoodsAjaxData: function (index, isInit,fn) {
            var _this = this;
            var nowStart = 0;
            var nowLimit = 0;

            if(index == 0 && isInit) {
                nowStart = perLimit;
                nowLimit = perLimit *  (ajaxData.pagearr - 1);
            }else if(index == 0 && !isInit) {
                nowStart = perLimit * ajaxData.pagearr;
                nowLimit = perLimit;
            }else if(isInit){
                nowStart = 0;
                nowLimit = perLimit * ajaxData.pagearr;
            }else{
                nowStart = perLimit * ajaxData.pagearr;
                nowLimit = perLimit;
            }

            var dataUrl = BASE_URL;
            var data = {};
            if(index == 0){
                dataUrl += "/shop/goods/loadGoods";
                data = {groupName:GROUP_NAME,start:nowStart,limit:nowLimit};
            }else if(index <= categoryData.length){
                dataUrl += "/category/loadAll";
                data = {categoryId:categoryData[index-1],start:nowStart,limit:nowLimit};
            }else{
                return;
            }

            G_JSON_POST(dataUrl,data,function (data) {
                if( data.length > 0 ) {
                    if(index == 0) {
                        connectHtml.GoodsLiHtml(data, index, 'showTwo')
                    } else {
                        connectHtml.GoodsLiHtml(data, index, 'showOne')
                    }
                    if(fn)fn()
                }

                if(data.length < nowLimit){
                    $('.js_slidePageMain').find('.js_loadingBtn').hide().eq(0).show();
                    ajaxData.loadFinish = true;
                }

            }, function () {
                // start
            }, function () {
                // end
            });

        },

        // 历史数据定位
        HistoryInit : function (fn1, fn2) {
            var _this = this;
            if(sessionStorage.getItem("pageScroll") != null) {
                _this.GetSessionData();
                ajaxData.HisScrollTop();
            }
            else {
                if(fn2) fn2();
            }
        },

        // 历史滚动高度
        HisScrollTop: function () {
            var oSlidePageScroll = $(window);
            if(sessionStorage.getItem("pageScroll") != null) {
                var pageScrollNum = parseInt(sessionStorage.getItem("pageScroll"));
                oSlidePageScroll.scrollTop(pageScrollNum);
            }
        },

        // 设置历史定位
        SetSession: function () {
            var _this = this;
            sessionStorage.setItem("pagearr", _this.pagearr);
            sessionStorage.setItem("pageScroll", _this.pageScroll);
        },

        // 记录数据历史数据
        GetSessionData: function() {
            var _this = this;
            if(sessionStorage.getItem("pageScroll") != null) {
                var pageNum = sessionStorage.getItem("pagearr");
                var pageScrollNum = sessionStorage.getItem("pageScroll");
                    ajaxData.pagearr = parseInt(pageNum);
                    //设置页面的数据
                    ajaxData.pageScroll = parseInt(pageScrollNum);
            }
        }

    }

    var sfddjIndex = {
        // 页面swiper
        oSlidePageMain: '',
        nHeaderHeight: 0,
        nSearchBoxHeight: 0,
        nSildeNavHeight: 0,
        time_Scroll: null,           // 滚动计时器
        // 调整页面位置和初始化
        sfddjInit: function (bOff) {
            // bOff true 执行下面方法
            if(bOff) {
                oContain.css({
                    'padding-top': oHeader.outerHeight(true),
                    'padding-bottom' : oFooter.outerHeight(true)
                });
                adsModel.adsInit.SetAdsLiScroll();
                myPub.SetImgHeight(oGoods_showTwo);
            }
            oSideBox.stop().animate({'right': '-3.5rem'},300);
        },


        // 滚动隐藏搜索
        ScrollPage: function () {
            var _this = this;
            var minScrHeight = 300;

            oWindow.on('scroll', function () {
                var afterScroll = $(this).scrollTop();
                // 滚动页面距离底部300像素 延迟150毫秒加载数据
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function() {
                    // 设置缓存记录
                    ajaxData.pageScroll = afterScroll;

                    if($('html')[0].scrollHeight - afterScroll - oWindow.height() < minScrHeight) {
                        // 设置翻页到最后一页 返回
                        if(ajaxData.loadFinish) {
                            $('.js_slidePageMain').find('.js_loadingBtn').hide().eq(0).show();
                            return;
                        }

                        // 加载产品数据
                        ajaxData.GoodsAjaxData(0, false, function () {
                            ajaxData.pagearr ++
                        });
                    }
                },150);
            })

        },


        //点击搜索按钮弹出搜索层
        showSearchBox:function () {
            oShowSearchBox.on('click',function (e) {
                $('.js_searchRecom').show();
                $('.js_searchTxt').focus();
                e.stopPropagation();
            })

            oClearSear.on('click',function () {
                $('.js_searchRecom').hide();
                $('.js_shadow').hide();
                e.stopPropagation();
            });

        }

    }


    // 拼接HTML
    var connectHtml = {
        // 产品容器（并排和一排）
        GoodHtmlBox: function (data, bOff) {
            var _selet = bOff;          //showTwo 并排  showOne 是一排
            var shmtlBox = '';
            var shmtlLoad = '';
            var goodsOneClass = 'js_goods_showOne';
            var goodsTwoClass = 'active js_goods_showTwo';

            function  setGoodsHtmlBox(aClassName) {
                if(aClassName == goodsOneClass) {
                    shmtlLoad =
                        '<div class="moreBtnBox">'+
                        '   <p class="loadingBtn js_loadingBtn" style="display:none;"><a>没有更多</a></p>'+
                        '   <p class="loadingBtn js_loadingBtn">'+
                        '       <span class="icon_loading icoStyle icon-spinner3 myRotateRefresh"></span>'+
                        '       <span>加载中</span>'+
                        '   </p>'+
                        '</div>';
                }

                return shmtlBox =
                    '<div class="goods_showChangeBox '+ aClassName +' js_goodsAddQuick">'+
                    '   <div class="goods_showChange">'+
                    '       <ul class="goodsList clearfix js_goodsList"></ul>'+
                    '   </div>'+
                        shmtlLoad +
                    '</div>';
            }

            if(_selet == 'showTwo') {
                return setGoodsHtmlBox(goodsTwoClass)
            }
            else if(_selet == 'showOne') {
                return setGoodsHtmlBox(goodsOneClass)
            }
            else {
                return setGoodsHtmlBox(goodsOneClass)
            }
        },
        // 并排产品列表
        GoodsLiHtml: function (data, iNow, showNum) {
            var _this = this;
            var oSlidePageScroll = $('.js_slidePageScroll');
            var shtml = '';
            var sfindClass = '';

            showNum == 'showTwo' ? sfindClass = 'js_goods_showTwo' : sfindClass = 'js_goods_showOne';

            var oGoodsShowLi = oSlidePageScroll.eq(iNow).find('.'+ sfindClass +'');

            // 判断是否需要放入容器和标题
            if(oGoodsShowLi.length == 0) {
                // 插入产品容器
                oSlidePageScroll.find('.js_insertNewContain').eq(iNow).append(_this.GoodHtmlBox(data, showNum));

                oGoodsShowLi = oSlidePageScroll.eq(iNow).find('.'+ sfindClass +'');
                // 插入产品标题
                oGoodsShowLi.prepend(adsModel.adsHtml.TitleHtml(data, 'time'))
            }


            for (var i=0; i<data.length; i++) {
                var goodsImgUrl = data[i].showImage != undefined ? (HTTP_IMAGE_URL + data[i].showImage) : (BASE_URL + '/static_v4/image/loadImg.jpg');
                shtml +=
                    '<li>' +
                    '   <a class="BoxSelf" href="' + BASE_URL + '/h/goodspay/goodsView/' + data[i].goodsSn + '" data-growing-title="'+data[i].name+'">'+
                    '       <figure>'+
                    '           <img class="js_lazyImg" data-echo="' + goodsImgUrl + smallImgArg + '" src="' + BASE_URL + 'static_v4/image/loadImg.jpg"  data-growing-title="'+data[i].name+'">'+
                    // '           <i class="tip-info">' + data[i].discount + '</i>'+
                    '       </figure>'+
                    '       <aside class="priceArea VBox Bflex1">'+
                    '           <div class="Bflex1 priceArea_name">'+
                    '               <h4>' + data[i].name + '</h4>'+
                    '               <p class="smallFont_tip">' + data[i].title + '</p>'+
                    '           </div>'+
                    '           <div class="priceArea_price">'+
                    // '               <i class="tip-info">' + data[i].discount + '</i>'+
                    '               <p class="HBox priceAreaBox">'+
                    // '                   <span class="goodsPriceOld">￥' + data[i].oldPrice + '</span>'+
                    '                   <span class="goodsPrice">￥' + data[i].salePrice + '</span>'+
                    '               </p>'+
                    '           </div>'+
                    '       </aside>'+
                    '   </a>'+
                    '   <p class="addCar js_addCar" pid="' + data[i].productId + '"><em class="icon-shopcar_small"></em></p>'+
                    '</li>';
            }

            var oShtml = $(shtml);

            oGoodsShowLi.find('.js_goodsList').append(oShtml);
            myPub.SetImgHeight(oShtml);
            lazLoading.DestroyLazLoadingImg();
            lazLoading.AddLazLoadingImg(oWrap[0]);
            shtml = null;
            oGoodsShowLi = null;
            oSlidePageScroll = null;
            data = null;
        }
    }
});